/**
 * @Title: CR.java
 * @Package com.kaver.tmd.kit.utils
 * @author roc
 * @date 2020年3月10日 上午10:03:20
 * @version V1.0
 * @copyright kaver
 */
package com.kaver.sso.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @ClassName: CR
 * @Description: 当前请求
 * @author roc
 * @date 2020年3月10日 上午10:03:20
 * 
 */
public class CR {

    /**
     * 获取当前线程HttpServlet请求对象
     */
    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前请求的地址
     */
    public static String getMappingPath() {
        HttpServletRequest request = getCurrentRequest();
        return StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
    }

    /**
     * 获取当前请求ip地址
     */
    public static String getIp() {
        HttpServletRequest request = getCurrentRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP的情况（只取第一个IP）
        if (ip != null && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            ip = ipArray[0];
        }
        return ip;
    }
}
